<template>
  <div class="app-container">
    <!-- 查询条件 -->
    <el-form :model="queryParams" ref="queryForm" size="small" label-width="100px" inline>
      <el-form-item label="发货单号" prop="deliveryCode">
        <el-input v-model="queryParams.deliveryCode" placeholder="请输入发货单号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="看板编码" prop="kanbanCode">
        <el-input v-model="queryParams.kanbanCode" placeholder="请输入看板编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="协议编码" prop="frameworkCode">
        <el-input v-model="queryParams.frameworkCode" placeholder="请输入协议编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 180px">
          <el-option v-for="opt in statusOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="需求到货时间">
        <el-date-picker v-model="dateRange" type="daterange" value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 320px" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 工具栏 -->
    <el-row :gutter="10" class="mb10">
      <el-col :span="12">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增发货</el-button>
        <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport">导出发货单</el-button>
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="ids.length === 0" @click="handleBatchDelete">批量删除</el-button>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="发货单号" align="center" prop="deliveryCode" min-width="140" />
      <el-table-column label="看板编码" align="center" prop="kanbanCode" min-width="120" />
      <el-table-column label="协议编码" align="center" prop="frameworkCode" min-width="120" />
      <el-table-column label="物料编码" align="center" prop="materialCode" min-width="120" />
      <el-table-column label="物料名称" align="center" prop="materialName" min-width="160" />
      <el-table-column label="单位" align="center" prop="materialUnit" width="80" />
      <el-table-column label="实发数量" align="center" prop="actualDeliveryQty" width="100" />
      <el-table-column label="需求到货时间" align="center" prop="requiredDeliveryTime" min-width="160">
        <template slot-scope="scope">{{ scope.row.requiredDeliveryTime }}</template>
      </el-table-column>
      <el-table-column label="实际到货时间" align="center" prop="actualDeliveryTime" min-width="160">
        <template slot-scope="scope">{{ scope.row.actualDeliveryTime }}</template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <el-tag :type="statusTagType(scope.row.status)" size="small">{{ statusLabel(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="异常" align="center" prop="exceptionFlag" width="80">
        <template slot-scope="scope">{{ scope.row.exceptionFlag === 1 ? '是' : '否' }}</template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" min-width="160">
        <template slot-scope="scope">{{ scope.row.createTime }}</template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="220" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)">详情</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 新增/编辑 抽屉 -->
    <el-drawer :title="form.id ? '修改发货单' : '新增发货单'" :visible.sync="openAdd" direction="rtl" size="50%" :wrapper-closable="false">
      <div style="padding: 0 20px 20px 20px">
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="发货单号" prop="deliveryCode">
                <el-input v-model="form.deliveryCode" placeholder="系统自动生成，不可修改" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="看板编码" prop="kanbanCode">
                <el-input v-model="form.kanbanCode" placeholder="请输入看板编码" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="协议编码" prop="frameworkCode">
                <el-input v-model="form.frameworkCode" placeholder="请输入协议编码" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="箱标签码" prop="boxLabelCode">
                <el-input v-model="form.boxLabelCode" placeholder="可来自扫码" />
              </el-form-item>
            </el-col>

            <!-- 仓库下拉置于公司之上，并自动填充公司 -->
            <!-- 左：发货 / 右：收货 -->
            <el-col :span="12">
            <el-form-item label="发货仓库" prop="senderWarehouseId">
                <treeselect
                  v-model="form.senderWarehouseId"
                  :options="deptOptions"
                  :normalizer="normalizer"
                  placeholder="请选择发货仓库"
                  @input="onSenderWarehouseSelect"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
            <el-form-item label="收货仓库" prop="receiverWarehouseId">
                <treeselect
                  v-model="form.receiverWarehouseId"
                  :options="deptOptions"
                  :normalizer="normalizer"
                  placeholder="请选择收货仓库"
                  @input="onReceiverWarehouseSelect"
                />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="发货公司" prop="senderCompanyName">
                <el-input v-model="form.senderCompanyName" placeholder="选择仓库后自动填充" :disabled="true" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="收货公司" prop="receiverCompanyName">
                <el-input v-model="form.receiverCompanyName" placeholder="选择仓库后自动填充" :disabled="true" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="物料编码" prop="materialCode">
                <el-input v-model="form.materialCode" placeholder="请输入物料编码" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="物料名称" prop="materialName">
                <el-input v-model="form.materialName" placeholder="请输入物料名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="单位" prop="materialUnit">
                <el-input v-model="form.materialUnit" placeholder="如：PCS/箱等" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="包装容量" prop="packageCapacity">
                <el-input-number v-model="form.packageCapacity" :min="0" :precision="3" :step="1" controls-position="right" style="width: 100%" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="实发数量" prop="actualDeliveryQty">
                <el-input-number v-model="form.actualDeliveryQty" :min="0" :precision="3" :step="1" controls-position="right" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="单价" prop="unitPrice">
                <el-input-number v-model="form.unitPrice" :min="0" :precision="3" :step="1" controls-position="right" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="税率(%)" prop="taxRate">
                <el-input-number v-model="form.taxRate" :min="0" :precision="2" :step="1" controls-position="right" style="width: 100%" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="需求到货时间" prop="requiredDeliveryTime">
                <el-date-picker v-model="form.requiredDeliveryTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择时间" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="实际到货时间" prop="actualDeliveryTime">
                <el-date-picker v-model="form.actualDeliveryTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择时间" style="width: 100%" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="状态" prop="status">
                <el-select v-model="form.status" placeholder="请选择" style="width: 100%">
                  <el-option v-for="opt in statusOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="异常标记" prop="exceptionFlag">
                <el-switch v-model="exceptionSwitch" active-text="是" inactive-text="否" @change="onExceptionSwitchChange" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="异常说明" prop="exceptionDescription">
                <el-input type="textarea" :rows="3" v-model="form.exceptionDescription" placeholder="异常说明" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div style="text-align: right">
          <el-button @click="cancelForm">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 详情 抽屉 -->
    <el-drawer title="发货单详情" :visible.sync="openDetail" direction="rtl" size="50%" :wrapper-closable="false">
      <div style="padding: 0 20px 20px 20px">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="发货单号">{{ detail.deliveryCode }}</el-descriptions-item>
          <el-descriptions-item label="看板编码">{{ detail.kanbanCode }}</el-descriptions-item>
          <el-descriptions-item label="协议编码">{{ detail.frameworkCode }}</el-descriptions-item>
          <el-descriptions-item label="箱标签码">{{ detail.boxLabelCode }}</el-descriptions-item>
          <el-descriptions-item label="收货公司">{{ detail.receiverCompanyName }}</el-descriptions-item>
          <el-descriptions-item label="发货公司">{{ detail.senderCompanyName }}</el-descriptions-item>
          <el-descriptions-item label="收货仓库">{{ detail.receiverWarehouse }}</el-descriptions-item>
          <el-descriptions-item label="发货仓库">{{ detail.senderWarehouse }}</el-descriptions-item>
          <el-descriptions-item label="物料编码">{{ detail.materialCode }}</el-descriptions-item>
          <el-descriptions-item label="物料名称">{{ detail.materialName }}</el-descriptions-item>
          <el-descriptions-item label="单位">{{ detail.materialUnit }}</el-descriptions-item>
          <el-descriptions-item label="包装容量">{{ detail.packageCapacity }}</el-descriptions-item>
          <el-descriptions-item label="实发数量">{{ detail.actualDeliveryQty }}</el-descriptions-item>
          <el-descriptions-item label="单价">{{ detail.unitPrice }}</el-descriptions-item>
          <el-descriptions-item label="税率(%)">{{ detail.taxRate }}</el-descriptions-item>
          <el-descriptions-item label="需求到货时间">{{ detail.requiredDeliveryTime }}</el-descriptions-item>
          <el-descriptions-item label="实际到货时间">{{ detail.actualDeliveryTime }}</el-descriptions-item>
          <el-descriptions-item label="状态">{{ statusLabel(detail.status) }}</el-descriptions-item>
          <el-descriptions-item label="异常">{{ detail.exceptionFlag === 1 ? '是' : '否' }}</el-descriptions-item>
          <el-descriptions-item label="异常说明">{{ detail.exceptionDescription }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { listDeliveryOrder, getDeliveryOrder, addDeliveryOrder, updateDeliveryOrder, delDeliveryOrder } from '@/api/kanban/deliveryOrder'
import { addDateRange } from '@/utils/ruoyi'
import { download } from '@/utils/request'
import { generateTempSequenceNumber, generateFormalSequenceNumber } from '@/api/kanban/sequence'
import { listDept } from '@/api/system/dept'
import Treeselect from "@riophae/vue-treeselect"
import "@riophae/vue-treeselect/dist/vue-treeselect.css"

export default {
  name: 'KanbanDeliveryOrder',
  components: { Treeselect },
  data() {
    return {
      loading: false,
      total: 0,
      list: [],
      ids: [],
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deliveryCode: undefined,
        kanbanCode: undefined,
        frameworkCode: undefined,
        status: undefined,
        params: {}
      },
      // 新增/编辑
      openAdd: false,
      form: {
        id: undefined,
        deliveryCode: undefined,
        kanbanCode: undefined,
        frameworkCode: undefined,
        boxLabelCode: undefined,
        receiverCompanyName: undefined,
        senderCompanyName: undefined,
        receiverCompanyId: undefined,
        senderCompanyId: undefined,
        receiverWarehouse: undefined,
        senderWarehouse: undefined,
        receiverWarehouseId: undefined,
        senderWarehouseId: undefined,
        materialCode: undefined,
        materialName: undefined,
        materialUnit: undefined,
        packageCapacity: 1,
        actualDeliveryQty: undefined,
        unitPrice: 0,
        taxRate: 0,
        requiredDeliveryTime: undefined,
        actualDeliveryTime: undefined,
        status: 10,
        exceptionFlag: 0,
        exceptionDescription: undefined
      },
      // 前端流水号生成状态
      seqKeyPrefix: 'SH',
      exceptionSwitch: false,
      rules: {
        kanbanCode: [{ required: false, message: '请输入看板编码', trigger: 'blur' }],
        frameworkCode: [{ required: false, message: '请输入协议编码', trigger: 'blur' }],
        materialCode: [{ required: true, message: '请输入物料编码', trigger: 'blur' }],
        materialName: [{ required: true, message: '请输入物料名称', trigger: 'blur' }],
        materialUnit: [{ required: true, message: '请输入单位', trigger: 'blur' }],
        actualDeliveryQty: [{ required: true, message: '请输入实发数量', trigger: 'blur' }],
        requiredDeliveryTime: [{ required: true, message: '请选择需求到货时间', trigger: 'change' }],
        senderWarehouseId: [{ required: true, message: '请选择发货仓库', trigger: 'change' }],
        receiverWarehouseId: [{ required: true, message: '请选择收货仓库', trigger: 'change' }]
      },
      // 详情
      openDetail: false,
      detail: {},
      // 部门/仓库下拉
      deptOptions: [],
      statusOptions: [
        { label: '未发货', value: 10 },
        { label: '已发货', value: 20 },
        { label: '已签收', value: 30 },
        { label: '异常', value: 99 }
      ]
    }
  },
  created() {
    this.getList()
    this.loadDeptOptions()
  },
  methods: {
    getList() {
      this.loading = true
      // 兼容后端 Controller 对顶层 begin/endRequiredDeliveryTime 的读取
      const params = { ...this.queryParams }
      if (Array.isArray(this.dateRange) && this.dateRange.length === 2) {
        params.beginRequiredDeliveryTime = this.dateRange[0]
        params.endRequiredDeliveryTime = this.dateRange[1]
      }
      listDeliveryOrder(params).then(res => {
        this.list = res.rows || []
        this.total = res.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.dateRange = []
      this.queryParams.deliveryCode = undefined
      this.queryParams.kanbanCode = undefined
      this.queryParams.frameworkCode = undefined
      this.queryParams.status = undefined
      if (this.$refs.queryForm) this.$refs.queryForm.resetFields()
      this.handleQuery()
    },

    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
    },

    handleAdd() {
      this.resetForm()
      this.openAdd = true
      this.loadDeptOptions()
      // 打开抽屉即生成临时发货单号（不占用后端流水）
      // 等表单渲染完成再生成，避免异步重置影响显示
      this.$nextTick(() => {
        this.generateTempDeliveryCode()
      })
    },
    handleUpdate(row) {
      this.resetForm()
      // 先加载部门树，再填充表单并映射下拉选中项
      Promise.all([this.loadDeptOptions(), getDeliveryOrder(row.id)]).then(([_, res]) => {
        const data = (res && res.data) || {}
        this.form = Object.assign({}, this.form, data)
        this.exceptionSwitch = this.form.exceptionFlag === 1
        this.form.receiverWarehouseId = this.findNodeIdByName(this.deptOptions, this.form.receiverWarehouse)
        this.form.senderWarehouseId = this.findNodeIdByName(this.deptOptions, this.form.senderWarehouse)
        // 映射公司ID作为兜底（后端若未返回或名称变更导致缺失）
        const recvNode = this.findNodeById(this.deptOptions, this.form.receiverWarehouseId)
        const recvCompany = this.findCompanyNode(recvNode)
        if (!this.form.receiverCompanyId) {
          this.form.receiverCompanyId = recvCompany ? recvCompany.deptId : (recvNode ? recvNode.deptId : undefined)
        }
        const sendNode = this.findNodeById(this.deptOptions, this.form.senderWarehouseId)
        const sendCompany = this.findCompanyNode(sendNode)
        if (!this.form.senderCompanyId) {
          this.form.senderCompanyId = sendCompany ? sendCompany.deptId : (sendNode ? sendNode.deptId : undefined)
        }
        this.openAdd = true
      })
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) return
        const payload = Object.assign({}, this.form)
        // 将异常开关映射到整数标识
        payload.exceptionFlag = this.exceptionSwitch ? 1 : 0
        if (!payload.id) {
          // 新增：提交前生成正式流水号（更新后端序列），与供货协议方式一致
          const seqKey = this.buildSeqKey()
          generateFormalSequenceNumber(seqKey, 4).then(response => {
            if (response && response.code === 200) {
              // 兼容后端返回在 data 或 msg 字段的两种情况
              payload.deliveryCode = response.data || response.msg
              return addDeliveryOrder(payload)
            } else {
              this.$modal && this.$modal.msgError('生成发货单号失败')
              return Promise.reject(new Error('Sequence generation failed'))
            }
          }).then(() => {
            this.$message.success('保存成功')
            this.openAdd = false
            this.getList()
          }).catch(() => {
            this.$message.error('保存失败，请重试')
          })
        } else {
          // 编辑：不变更发货单号
          updateDeliveryOrder(payload).then(() => {
            this.$message.success('保存成功')
            this.openAdd = false
            this.getList()
          })
        }
      })
    },
    cancelForm() {
      this.openAdd = false
    },
    resetForm() {
      this.form = {
        id: undefined,
        deliveryCode: undefined,
        kanbanCode: undefined,
        frameworkCode: undefined,
        boxLabelCode: undefined,
        receiverCompanyName: undefined,
        senderCompanyName: undefined,
        receiverCompanyId: undefined,
        senderCompanyId: undefined,
        receiverWarehouse: undefined,
        senderWarehouse: undefined,
        receiverWarehouseId: undefined,
        senderWarehouseId: undefined,
        materialCode: undefined,
        materialName: undefined,
        materialUnit: undefined,
        packageCapacity: 1,
        actualDeliveryQty: undefined,
        unitPrice: 0,
        taxRate: 0,
        requiredDeliveryTime: undefined,
        actualDeliveryTime: undefined,
        status: 10,
        exceptionFlag: 0,
        exceptionDescription: undefined
      }
      this.exceptionSwitch = false
      if (this.$refs.form) this.$refs.form.clearValidate()
    },

    handleView(row) {
      getDeliveryOrder(row.id).then(res => {
        this.detail = res.data || {}
        this.openDetail = true
      })
    },

    handleDelete(row) {
      const ids = row && row.id ? row.id : this.ids.join(',')
      if (!ids) return
      this.$confirm('是否确认删除选中的发货单？', '提示', { type: 'warning' }).then(() => {
        delDeliveryOrder(ids).then(() => {
          this.$message.success('删除成功')
          this.getList()
        })
      })
    },
    handleBatchDelete() {
      this.handleDelete()
    },

    handleExport() {
      const params = { ...this.queryParams }
      if (Array.isArray(this.dateRange) && this.dateRange.length === 2) {
        params.beginRequiredDeliveryTime = this.dateRange[0]
        params.endRequiredDeliveryTime = this.dateRange[1]
      }
      download('/kanban/deliveryOrder/export', params, `delivery_order_${new Date().getTime()}.xlsx`)
    },

    onExceptionSwitchChange(val) {
      // 同步异常开关到表单，并在关闭时清空异常描述
      this.exceptionSwitch = val
      this.form.exceptionFlag = val ? 1 : 0
      if (!val) {
        this.form.exceptionDescription = undefined
      }
    },

    statusLabel(val) {
      const found = this.statusOptions.find(s => s.value === val)
      return found ? found.label : val
    },
    statusTagType(val) {
      switch (val) {
        case 10: return 'info'
        case 20: return 'warning'
        case 30: return 'success'
        case 99: return 'danger'
        default: return 'default'
      }
    },
    // ===== 发货单号自动生成（SH+YYYYMMDD+4位序号） =====
    formatDateYYYYMMDD(d) {
      const y = d.getFullYear()
      const m = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')
      return `${y}${m}${day}`
    },
    buildSeqKey() {
      return `${this.seqKeyPrefix}${this.formatDateYYYYMMDD(new Date())}`
    },
    generateTempDeliveryCode() {
      const seqKey = this.buildSeqKey()
      this.form.deliveryCode = undefined
      generateTempSequenceNumber(seqKey, 4).then(response => {
        if (response && response.code === 200) {
          // 与供货协议保持一致：直接使用后端返回的完整编码字符串
          // 兼容后端返回在 data 或 msg 字段的两种情况
          this.form.deliveryCode = response.data || response.msg
        } else {
          this.$modal && this.$modal.msgError('生成发货单号失败')
        }
      }).catch(err => {
        console.error('生成临时发货单号失败:', err)
        this.$modal && this.$modal.msgError('生成发货单号失败')
      })
    },
    // ===== 部门树/仓库选择 =====
    loadDeptOptions() {
      return listDept().then(response => {
        this.deptOptions = this.handleTree(response.data, 'deptId')
        return this.deptOptions
      })
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      }
    },
    findNodeById(nodes, id) {
      for (let n of nodes) {
        if (n.deptId === id) return n
        if (n.children && n.children.length) {
          const f = this.findNodeById(n.children, id)
          if (f) return f
        }
      }
      return null
    },
    findCompanyNode(node) {
      if (!node) return null
      if (node.parentId === 0 || node.parentId === 100) return node
      const parent = this.findNodeById(this.deptOptions, node.parentId)
      return parent ? this.findCompanyNode(parent) : null
    },
    onReceiverWarehouseSelect(value) {
      if (!value) {
        this.form.receiverWarehouse = undefined
        this.form.receiverCompanyName = undefined
        this.form.receiverCompanyId = undefined
        return
      }
      const selected = this.findNodeById(this.deptOptions, value)
      if (selected) {
        this.form.receiverWarehouse = selected.deptName
        const company = this.findCompanyNode(selected)
        this.form.receiverCompanyName = company ? company.deptName : selected.deptName
        this.form.receiverCompanyId = company ? company.deptId : selected.deptId
      }
    },
    onSenderWarehouseSelect(value) {
      if (!value) {
        this.form.senderWarehouse = undefined
        this.form.senderCompanyName = undefined
        this.form.senderCompanyId = undefined
        return
      }
      const selected = this.findNodeById(this.deptOptions, value)
      if (selected) {
        this.form.senderWarehouse = selected.deptName
        const company = this.findCompanyNode(selected)
        this.form.senderCompanyName = company ? company.deptName : selected.deptName
        this.form.senderCompanyId = company ? company.deptId : selected.deptId
      }
    },
    findNodeIdByName(nodes, name) {
      if (!name) return undefined
      for (let n of nodes) {
        if (n.deptName === name) return n.deptId
        if (n.children && n.children.length) {
          const id = this.findNodeIdByName(n.children, name)
          if (id) return id
        }
      }
      return undefined
    }
  }
}
</script>

<style scoped>
.mb8 { margin-bottom: 8px; }
</style>